<?php

namespace App\B2BProject\Custom;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use App\B2BProject\Custom\Member;

/**
 * Class AuthorizationRequest
 *
 * 采购商申请授权模型
 *
 * @package App\B2BProject\Custom
 */
class AuthorizationRequest extends Model
{
    protected $guarded = ['id', 'created_at', 'updated_at'];

    /**
     * 对应的商品授权表，用于当前授权请求下的所有授权商品
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function licensedGoods()
    {
        return $this->hasMany('App\B2BProject\Custom\Business\LicensedGood', 'authorization_id', 'id');
    }

    /**
     * 获取该授权所关联的供应商
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function provider()
    {
        return $this->belongsTo('App\B2BProject\Custom\Provider', 'provider_id', 'id');
    }

    /**
     * 获取该授权所关联的采购商
     */
    public function purchaser()
    {
        return $this->belongsTo('App\B2BProject\Custom\Purchaser', 'purchaser_id', 'id');
    }

    /**
     * 根据状态和过期时间判断，取出当前的有效授权信息
     *
     * @param Builder $builder
     * @param Member|int $purchaser 采购商对象或ID
     * @param Member|int $provider 供应商对象或ID
     *
     * @return Builder
     */
    public function scopeAvailable(Builder $builder, $purchaser = null, $provider = null)
    {
        $builder = $builder->where('status', 2)->where('authorize_stop', '>=', date('Y-m-d', time()));
        if (is_null($purchaser) && is_null($provider)) {
            return $builder;
        }

        if (!is_null($purchaser)) {
            if (!($purchaser instanceof Member)) {
                $builder = $builder->where('purchaser_id', $purchaser);
            } else {
                $builder = $builder->where('purchaser_id', $purchaser->id);
            }
        }

        if (!is_null($provider)) {
            if (!($provider instanceof Member)) {
                $builder = $builder->where('provider_id', $provider);
            } else {
                $builder = $builder->where('provider_id', $provider->id);
            }
        }

        return $builder;
    }

    public function scopeDisplay(Builder $builder)
    {
        return $builder->where('status', 2);
    }

    /**
     * 获取正在申请中的记录
     *
     * @param Builder $builder
     *
     * @return $this
     */
    public function scopePending(Builder $builder)
    {
        return $builder->where('status', 1)->where('purchaser_id', \Auth::user()->id);
    }

    /**
     * 获取当前授权状态
     *
     * 0 未授权 1 合作中 2 已过期
     *
     * @return int
     */
    public function getAuthorizationStatus()
    {
        if (strtotime($this->authorize_stop) - time() < 0) {
            $this->process_status = 2; // 设置过程状态为：已过期
            $this->save();
        }

        return $this->process_status;
    }

}
